package com.hsurosy.hsuchain.nft.base.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;

/**
 * 参数校验工具类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-04 18:50
 * @Description
 * @Version: v1.0.0
 */
public class BeanValidator {

    /**
     * Hibernate 校验器，配置为快速失败模式
     */
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure()
            .failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验对象的字段是否合法
     *
     * @param object 待校验的对象
     * @param groups 校验分组
     * @throws ValidationException 如果校验失败，抛出校验异常
     */
    public static void validateObject(Object object, Class<?>... groups) throws ValidationException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (constraintViolations.stream().findFirst().isPresent()) {
            throw new ValidationException(constraintViolations.stream().findFirst().get().getMessage());
        }
    }
}
